package com.jfirer.validator.constraint.validator;

import java.math.BigDecimal;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.constraints.Digits;

public class DigitsValidator implements ConstraintValidator<Digits, Number>
{
    private int maxIntegerLength;
    private int maxFractionLength;
    
    @Override
    public void initialize(Digits constraintAnnotation)
    {
        this.maxIntegerLength = constraintAnnotation.integer();
        this.maxFractionLength = constraintAnnotation.fraction();
        validateParameters();
    }
    
    @Override
    public boolean isValid(Number num, ConstraintValidatorContext constraintValidatorContext)
    {
        if (num == null)
        {
            return true;
        }
        BigDecimal bigNum;
        if (num instanceof BigDecimal)
        {
            bigNum = (BigDecimal) num;
        }
        else
        {
            bigNum = new BigDecimal(num.toString()).stripTrailingZeros();
        }
        int integerPartLength = bigNum.precision() - bigNum.scale();
        int fractionPartLength = bigNum.scale() < 0 ? 0 : bigNum.scale();
        return (maxIntegerLength >= integerPartLength && maxFractionLength >= fractionPartLength);
    }
    
    private void validateParameters()
    {
        if (maxIntegerLength < 0)
        {
            throw new UnsupportedOperationException("integer必须大于00");
        }
        if (maxFractionLength < 0)
        {
            throw new UnsupportedOperationException("fraction必须大于0");
        }
    }
}
